/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dttung
 */
public class Utils {
    public  final String yffscoresfn = "yff.txt";
    public  final String[] calsfn = {"cal1.txt", "cal2.txt", "cal3.txt", "cal4.txt", "cal5.txt"};
    public  final String leaguetblfn = "tab.txt";
    public  HashMap teamsscores = new HashMap();
    public  HashMap yffscores = new HashMap();
    public HashMap tmlscores = new HashMap();
    public String[] tmlteams = {"savapain", "XXX", "XRK","TungDauGau", "AS Dưa lê", "ORANJE", "Big Dreams", 
        "Batsach", "Bông FC", "SugarTea", "Chelsea_Vietnam", "LetGoAhead Utd"};
    public final String systemdir = "C:\\Users\\dttung\\Documents\\NetBeansProjects\\2013-2014\\src\\java\\";
    //public final String systemdir = "/Users/dttung/NetBeansProjects/trunk/2013-2014/src/java/";
    //public final String systemdir = "/var/lib/openshift/5224c8d94382ec6f2b00034b/jbossews/yff/";
    public HashMap teamlinks = new HashMap();
    public int[] yffweekstart_cup = {3, 11, 19, 26}; // Cup 1 bat dau tu tuan 3, cup 2 bat dau tu tuan 11
    /**
     * Read all yff scores from yff.txt to yffscores
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public void readYffScores() throws FileNotFoundException, IOException, URISyntaxException
    {
        //URL path = getClass().getResource("/var/lib/openshift/5224bea15004462ff400043f/jbossews/yff/yff.txt");
        File yffscorefile = new File(systemdir + "yff.txt");
        //BufferedReader reader = new BufferedReader(yffscorefile);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(yffscorefile),"UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            int pos = line.indexOf("|");
            String team = line.substring(0, pos);
            String scoresstr = line.substring(pos + 1, line.length());
            ArrayList<String> scoresList = new ArrayList<String>();
            pos = 0;
            while (pos != -1)
            {
                pos = scoresstr.indexOf("|");
                if (pos != -1)
                {
                    String score = scoresstr.substring(0, pos);
                    String scoresstrtmp = scoresstr.substring(pos + 1, scoresstr.length());
                    scoresstr = scoresstrtmp;
                    scoresList.add(score);
                } else // last found
                {
                    scoresList.add(scoresstr);
                }
            }
            String[] res = new String[scoresList.size()];
            scoresList.toArray(res);
            yffscores.put(team, res);
        }
        reader.close();
    }
    /**
     * Write all yff scores to file yff.txt
     * @throws IOException 
     */
    public void writeYffScores() throws IOException, URISyntaxException
    {        
        //URL path = getClass().getResource("yff.txt");
        //File yffscorefile = new File(path.toURI());
        File yffscorefile = new File(systemdir + "yff.txt");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(yffscorefile),"UTF-8"));
        Iterator it = yffscores.entrySet().iterator();
        while (it.hasNext())
        {
            Map.Entry pairs = (Map.Entry)it.next();
            String team = (String) pairs.getKey();
            //System.out.print(team + " = ");
            String[] scores= (String[]) pairs.getValue();
            writer.write(team);
            for (int i = 0 ; i < scores.length; i++)
            {
                writer.write("|" + scores[i]);
                System.out.print("|" + scores[i]);
            }
            writer.newLine();
        }
        writer.close();
        //yffscorefile.close();
        
    }
    /**
     * Read all league scores from tab.txt to teamsscores
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public void readTeamScores() throws FileNotFoundException, IOException, URISyntaxException
    {
        //URL path = getClass().getResource("tab.txt");
        //File teamscorefile = new File(path.toURI());
        File teamscorefile = new File(systemdir + "tab.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(teamscorefile),"UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            int pos = line.indexOf("|");
            String team = line.substring(0, pos);
            String score = line.substring(pos + 1, line.length());
            teamsscores.put(team, score);
        }
        reader.close();
        //teamscorefile.close();
    }
    public void initTeamScores() throws UnsupportedEncodingException, FileNotFoundException, IOException
    {
        File teamscorefile = new File(systemdir + "tab.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(teamscorefile),"UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            int pos = line.indexOf("|");
            String team = line.substring(0, pos);
            String score = "0|0|0|0|0|0";
            teamsscores.put(team, score);
        }
        reader.close();
    }
    /**
     * Read and create a map team - link from "teams.txt".
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     * @throws IOException 
     */
    public void readTeamLinks() throws FileNotFoundException, UnsupportedEncodingException, IOException
    {
        File teamsfile = new File(systemdir + "teams.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(teamsfile),"UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            int pos = line.indexOf("|");
            String team = line.substring(0, pos);
            String link = line.substring(pos + 1, line.length());
            teamlinks.put(team, link);
        }
        reader.close();
    }
    /**
     * Write all the league score in file tab.txt
     * @throws IOException 
     */
    public void writeTeamScores() throws IOException, URISyntaxException
    {
        //URL path = getClass().getResource("tab.txt");
        //File teamscorefile = new File(path.toURI());
        File teamscorefile = new File(systemdir + "tab.txt");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(teamscorefile),"UTF-8"));
        Iterator it = teamsscores.entrySet().iterator();
        while (it.hasNext())
        {
            Map.Entry pairs = (Map.Entry)it.next();
            String team = (String) pairs.getKey();
            String scores = (String) pairs.getValue();
            writer.write(team);
            writer.write("|" + scores);
            writer.newLine();
        }
        writer.close();
        //teamscorefile.close();
    }
    /**
     * Update yff score for a team in a round.
     * Need to call writeYff to update to file
     * @param team: The team that needs update score
     * @param yffpoint: The YFF point that the team got
     * @param round: The EPL round (1-index)
     */
    public void updateYffScore(String team, String yffpoint, int round)
    {
        String[] scores = (String[])yffscores.get(team);
        scores[round - 1] = yffpoint; // because of 0-index
        //yffscores.remove(team);
        //yffscores.put(team, scores);
    }
    /**
     * Update league score of a match team1 vs team2 in a round
     * @param match: the match that in format team1|team2
     * @param round: the EPL round
     */
    public void updateMatch(String match, int round)
    {
        int pos = match.indexOf("|");
        String team1 = match.substring(0, pos);
        String team2 = match.substring(pos + 1, match.length());
        // get score
        String[] yffscores1 = (String[])yffscores.get(team1);
        float yffscore1 = Float.valueOf(yffscores1[round - 1]);
        String[] yffscores2 = (String[])yffscores.get(team2);
        float yffscore2 = Float.valueOf(yffscores2[round - 1]);
        updateScore(team1, yffscore1, yffscore1 - yffscore2);
        updateScore(team2, yffscore2, yffscore2 - yffscore1);        
    }
    /**
     * Update all league scores for all matches after a round. Auto update to file tab.txt
     * @param matches
     * @param round 
     */
    public void updateMatches(ArrayList<String> matches, int round) throws IOException, URISyntaxException
    {
        for (int i = 0; i < matches.size(); i++)
        {
            updateMatch(matches.get(i), round);
        }
        writeTeamScores();
    }
    /**
     * Update league score for a team after a match.
     * @param team: The team that need to update score
     * @param diff: The difference the team gets in a match
     */
    public void updateScore(String team, float yffscore, float diff)
    {
        String score = (String)teamsscores.get(team);
        int winpos = score.indexOf("|");        
        int win = Integer.valueOf(score.substring(0, winpos));
        int drawpos = score.indexOf("|", winpos + 1);
        int draw = Integer.valueOf(score.substring(winpos + 1, drawpos));
        int loosepos = score.indexOf("|", drawpos + 1);
        int loose = Integer.valueOf(score.substring(drawpos + 1, loosepos));
        int pointpos = score.indexOf("|", loosepos + 1);
        int point = Integer.valueOf(score.substring(loosepos + 1, pointpos)); 
        int diffpos = score.indexOf("|", pointpos + 1);
        float currdiff = Float.valueOf(score.substring(pointpos + 1, diffpos));
        float curryff = Float.valueOf(score.substring(diffpos + 1, score.length()));
        if (diff >= 5) // Team win
        {
            win += 1;
            point += 3;
            //currdiff += diff; // update difference
        } else if (diff >= -4) // draw
        {
            draw += 1;
            point += 1;
            //currdiff += diff;
        } else // loose
        {
            loose += 1;
        }
        currdiff += diff; // update difference    
        curryff += yffscore; // update total yffscore
        
        score = String.valueOf(win) + "|"
                + String.valueOf(draw) + "|"
                + String.valueOf(loose) + "|"
                + String.valueOf(point) + "|"
                + String.valueOf(currdiff) + "|"
                + String.valueOf(curryff);
        teamsscores.remove(team);
        teamsscores.put(team, score);
    }
    public ArrayList<String> getMatches(int tour) throws FileNotFoundException, IOException, URISyntaxException
    {
        ArrayList<String> matches = new ArrayList<String>();
        // Read cal{tour}.txt   
        File f = new File(systemdir + calsfn[tour-1]);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f),"UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            matches.add(line);
        }
        return matches;
    }
    /**
     * Update TML scores.
     */
    public void updateTMLscores()
    {
        for (int i = 0; i < tmlteams.length; i++)
        {
            String team = tmlteams[i];
            String[] yffteamscores = (String[])yffscores.get(team);
            float totalyffscore = 0;
            for (int j = 0; j < yffteamscores.length; j++)
            {
                float score = Float.valueOf(yffteamscores[j]);
                totalyffscore += score;
            }
            tmlscores.put(team, totalyffscore);
        }
    }
    /**
     * Return current 1-indexed round.
     * @return 
     */
    public int getCurrentRound()
    {
        String team = "savapain";
        String[] savascores = (String[])yffscores.get(team);
        int i;
        for (i = 0; i<savascores.length; i++)
        {
            float score = Float.valueOf(savascores[i]);
            if (score == 0.0) return i;
        }
        return i;
    }
    /**
     * Return TML teams sorted by total YFF.
     */
    public TreeMap getSortedTMLTeamsOnTotalYFF()
    {
        TMLScoreComparator comp = new TMLScoreComparator(tmlscores);
        TreeMap sortedTeams = new TreeMap(comp);
        sortedTeams.putAll(tmlscores);
        return sortedTeams;
    }
    /**
     * Return a list of teams that get highest yff score in a week
     * @param week that look for 
     * @return list of teams
     */
    public ArrayList<String> getWeeklyHighestScoreTeams(int week)
    {
        HashMap weeklyTeamPoints = new HashMap();
        for (int i = 0; i < tmlteams.length; i++)
        {
            String team = tmlteams[i];
            String weekYffPoint = getWeekYffPoint(team, week);
            weeklyTeamPoints.put(team, Float.valueOf(weekYffPoint));
        }
        TMLScoreComparator comp = new TMLScoreComparator(weeklyTeamPoints);
        TreeMap sortedTeams = new TreeMap(comp);
        sortedTeams.putAll(weeklyTeamPoints);
        
        ArrayList<String> maxteams = new ArrayList<String>();
        
        Iterator it = sortedTeams.entrySet().iterator();
        
        Map.Entry pairs = (Map.Entry)it.next();
        String maxteam = (String) pairs.getKey();    
        maxteams.add(maxteam);
        float maxscore = (Float) pairs.getValue();
        
        while (it.hasNext())
        {
            pairs = (Map.Entry)it.next();
            String team = (String) pairs.getKey();
            float score = (Float) pairs.getValue();
            if (score != maxscore) break;
            else maxteams.add(team);
        }
        return maxteams;
    }
    /**
     * Get yff point of a team in week
     * @param team to get yff point
     * @param week to get yff point for team
     * @return yff point
     */
    public String getWeekYffPoint(String team, int week)
    {
        String[] teamyffscore = (String[])yffscores.get(team);
        return teamyffscore[week - 1]; // because of 0-index
    }

    public String getTeamLinkHtml(String team, String color)
    {
        String htmlstr = "<a href=\"" + teamlinks.get(team) + "\"><font color=\"" + color +"\">" + team + "</font></a>";        
        return htmlstr;
    }
    public String getTeamLinkHtml(String team)
    {
        String htmlstr = "<a href=\"" + teamlinks.get(team) + "\">" + team + "</a>";        
        return htmlstr;
    }
    public float getTotalYffPoint(String team)
    {
        String totalPoint = (String) teamsscores.get(team);
        int pos = totalPoint.lastIndexOf("|");
        return Float.valueOf(totalPoint.substring(pos + 1, totalPoint.length()));
    }
}
